Ext.define('BISC.view.FormCreateFilter', {
    extend: 'Ext.panel.Panel',
    alias: ['widget.formcreatefilter'],
    requires: [
        'BISC.view.FilterManagerRulesInput',
        'BISC.view.FilterManagerMonitorsInput',
        'BISC.view.FilterManagerAttributesInput'
    ],
    id: 'createFilterPanel',
    border: false,

    initComponent: function() {
        var me = this;

        var form = Ext.create('Ext.form.Panel',{
            id: 'formCreateFilter',
            bodyPadding: 10,
            border: false,
            items: [
                {
                    xtype: 'textfield',
                    id: 'filterNameField',
                    fieldLabel: 'Filter Name',
                    labelAlign: 'right',
                    anchor: '100%',
                    name: 'name'
                }
            ]
        });

        if ( this.filter.data ) {
            Ext.getCmp('formCreateFilter').loadRecord( this.filter );
            var parsedFilter = this.filter.get('data');
            try {
                parsedFilter = JSON.parse( parsedFilter );
            } catch ( err ) {
                // already parsed
            }
            parsedFilter.filterId = this.filter.get('filterId');
            this.filter = parsedFilter;
        }

        var monitorsForm = Ext.create( 'BISC.view.FilterManagerMonitorsInput', { mainForm: me } );
        var rulesForm = Ext.create( 'BISC.view.FilterManagerRulesInput', { mainForm: me } );
        var attributesForm = Ext.create( 'BISC.view.FilterManagerAttributesInput', { mainForm: me } );

        console.log( this.filter );
        Ext.applyIf(me, {
            items: [
                form,
                {
                    xtype: 'tabpanel',
                    activeTab: 0,
                    border: false,
                    items: [
                        monitorsForm,
                        rulesForm,
                        attributesForm
                    ]
                }
            ],
            dockedItems: [
                {
                    xtype: 'toolbar',
                    ui: 'footer',
                    dock: 'bottom',
                    items: [
                        '->',
                        {
                            xtype: 'button',
                            text: 'Cancel',
                            scope: this,
                            handler: this.cancel
                        },
                        {
                            xtype: 'button',
                            text: 'Simulate Filter',
                            scope: me,
                            handler: this.test
                        },
                        {
                            xtype: 'button',
                            text: ( this.filter.filterId ) ? 'Update Filter' : 'Add Filter',
                            scope: me,
                            handler: this.submit
                        }
                    ]
                } 
            ]
        });

        me.callParent(arguments);
    },
    test: function() {
        var me = this;
        var values = {
            name: Ext.getCmp('filterNameField').getValue(),
            enabled: 0
        };
        me.filter.name = values.name;
        values.data = JSON.stringify( me.filter );

        Ext.Ajax.request({
            method: 'POST',
            url: 'http://localhost:8888/testFilter',
            jsonData: values,
            scope: this,
            success: function( resObj ) {
                var res = Ext.decode( resObj.responseText );
                if ( res.success ) {
                    // clear any errors
                    if ( Ext.get('addCmpError') ) Ext.get('addCmpError').update( '' );
                    if ( Ext.get('addMonError') ) Ext.get('addMonError').update( '' );
                    if ( Ext.get('addAttrError') ) Ext.get('addAttrError').update( '' );
                    var me = this;
                    var tmpWindow = Ext.create('Ext.window.Window', {
                        title: 'Filter Simulation Results (' + res.data.length + ' matches.)',
                        iconCls: 'icon_simulation',
                        modal: true,
                        height: 500,
                        width: 800,
                        layout: 'fit',
                        scope: this,
                        items: [
                            {
                                xtype: 'panel',
                                autoScroll: true,
                                data: res.data,
                                tpl: new Ext.XTemplate( '<tpl for=".">' +
                                        '<div>{image.filepath}/{image.path}</div>' +
                                        '<div><tpl for="attributes">' +
                                            '<div style="margin-left: 20px;">{testInfo.prefix} <span style="color:{testInfo.color}; font-weight: bold;">{[this.printMainText(values)]}</span></div>' +
                                        '</tpl></div>' +
                                    '</tpl>', {
                                        printMainText: function( values ) {
                                            var string = ( typeof values.value == 'undefined' ) ? values.categoryTitle : values.value;
                                            if ( values.fields && values.fields.length > 0 ) {
                                                if ( values.value.charAt( values.value.length-1 ) != '/' ) string += '/';
                                                Ext.each( values.fields, function( field ) {
                                                    string += '<span style="font-weight:bold">' + field.text + '</span>/';
                                                });
                                                string += 'image.ext';
                                            }
                                            if ( !values.category && !values.fields ) {
                                                string = values.name;
                                            }
                                            return string;
                                        }
                                    }
                                )
                            }
                        ],
                        dockedItems: [
                            {
                                xtype: 'toolbar',
                                ui: 'footer',
                                dock: 'bottom',
                                scope: me,
                                items: [
                                    {
                                        xtype: 'button',
                                        text: 'Run Once',
                                        scope: me,
                                        handler: function() {
                                            var me = this;
                                            var values = {
                                                name: Ext.getCmp('filterNameField').getValue(),
                                                enabled: 0
                                            };
                                            me.filter.name = values.name;
                                            values.data = JSON.stringify( me.filter );
                                            Ext.getCmp('statusLabel').update('Initializing filter...');

                                            Ext.Ajax.request({
                                                method: 'POST',
                                                url: 'http://localhost:8888/runFilter',
                                                jsonData: values,
                                                scope: me,
                                                success: function( resObj ) {
                                                    var res = Ext.decode( resObj.responseText );
                                                    if ( res.success ) {
                                                        Ext.getCmp('statusLabel').update('Checking attributes...');
                                                    }
                                                }
                                            });
                                            tmpWindow.close();
                                        }
                                    },
                                    '->',
                                    {
                                        xtype: 'button',
                                        text: 'Close',
                                        handler: function() { this.ownerCt.ownerCt.fireEvent('done') }
                                    }
                                ]
                            }
                        ]
                    }).show();
                    tmpWindow.on( 'done', function( data ) {
                        tmpWindow.close();
                    });
                } else {
                    if ( Ext.get('addCmpError') ) Ext.get('addCmpError').update( res.error.message );
                    if ( Ext.get('addMonError') ) Ext.get('addMonError').update( res.error.message );
                    if ( Ext.get('addAttrError') ) Ext.get('addAttrError').update( res.error.message );
                }
            }
        });
    },
    submit: function() {
        var me = this;
        var values = {
            name: Ext.getCmp('filterNameField').getValue(),
            enabled: 0
        };
        if ( this.filter.filterId ) values.filterId = this.filter.filterId;
        me.filter.name = values.name;
        values.data = JSON.stringify( me.filter );
        var route = ( this.filter.filterId ) ? 'updateFilter' : 'addFilter';
        Ext.Ajax.request({
            method: 'POST',
            url: 'http://localhost:8888/' + route,
            jsonData: values,
            scope: this,
            success: function( resObj ) {
                var res = Ext.decode( resObj.responseText );
                if ( res.success ) {
                    this.ownerCt.fireEvent('done');
                } else {
                    if ( Ext.get('addCmpError') ) Ext.get('addCmpError').update( res.error.message );
                    if ( Ext.get('addMonError') ) Ext.get('addMonError').update( res.error.message );
                    if ( Ext.get('addAttrError') ) Ext.get('addAttrError').update( res.error.message );
                }
            }
        });
    },
    cancel: function() {
        this.ownerCt.fireEvent( 'done' );
    }
});
